package cn.cslg.weatherforecast;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CityActivity extends AppCompatActivity {
    OkHttpClient client = new OkHttpClient();
    private List<String> provinceList = new ArrayList<>();
    private List<String> cityList = new ArrayList<>();
    private JSONObject jsonObject;

    private NiceSpinner niceSpinner;
    private NiceSpinner niceSpinner2;
    private Button confirm_btn;

    String run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city);
        findViews();
        new MyTask().execute(R.string.province_url, null);
        new MyTask().execute(R.string.city_url, 1);
        setListeners();
    }

    private void setListeners() {
        confirm_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                String city = niceSpinner2.getSelectedItem().toString();
                intent.putExtra("city", city);

                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("cur_city", city);
                editor.commit();

                setResult(RESULT_OK, intent);
                finish();
            }
        });

        niceSpinner2.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
//                String item = (String) parent.getItemAtPosition(position);
                String res = "已选城市：" + parent.getItemAtPosition(position).toString();
                Toast.makeText(CityActivity.this, res, Toast.LENGTH_SHORT).show();
            }

        });

        niceSpinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
//                String item = (String) parent.getItemAtPosition(position);
                new MyTask().execute(R.string.city_url, position + 1);
            }
        });
    }

    private void findViews() {
        confirm_btn = findViewById(R.id.confirm_btn);
        niceSpinner = findViewById(R.id.nice_spinner);
        niceSpinner2 = findViewById(R.id.nice_spinner2);
    }

class MyTask extends AsyncTask {
    private int flag = 0;//0:省,1:市

    @Override
    protected Object doInBackground(Object[] objects) {
        //工作线程不能更新UI控件
        try {
            if (objects[1] == null) {
                return run(getResources().getString((Integer) objects[0]));
            } else {
                flag = 1;
                System.out.println("\nobjects[1]:" + getResources().getString((Integer) objects[0]) + objects[1]);
                return run(getResources().getString((Integer) objects[0]) + objects[1]);
            }//传递给onPostExecute
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        try {
            jsonObject = new JSONObject((String) o);
            if (jsonObject.getString("msg").equals("ok")) {
                JSONArray jsonArray = jsonObject.getJSONArray("result"); //result
                if (flag == 0) {
                    provinceList = new ArrayList<>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        provinceList.add(jsonArray.getJSONObject(i).getString("name"));
                        System.out.print(provinceList.get(i));
                    }
//                        ArrayAdapter adapter = new ArrayAdapter<>(CityActivity.this, android.R.layout.simple_dropdown_item_1line, provinceList);
//                        //                        System.err.println("province+" + provinceList.size());
//                        sp.setAdapter(adapter);
                    niceSpinner.attachDataSource(provinceList);
                } else if (flag == 1) {
                    cityList = new ArrayList<>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        cityList.add(jsonArray.getJSONObject(i).getString("name"));
                        System.out.print(cityList.get(i));
                    }
//                        ArrayAdapter adapter = new ArrayAdapter<>(CityActivity.this, android.R.layout.simple_dropdown_item_1line, cityList);
////                        System.err.println("city+" + cityList.size()); //0
//                        sp2.setAdapter(adapter);
                    niceSpinner2.attachDataSource(cityList);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
}
